# # 模式 a 追加，内容结尾处追加新内容
# with open('./files/test.txt','a',encoding='utf-8') as f:
#     f.write('这是追加的内容1\n')
#     f.write('这是追加的内容2\n')
#     f.write('这是追加的内容3\n')


# with open('./files/test.txt','r',encoding='utf-8') as f:
#     print(f.read())


"""
练习1

"""
# with open('./files/2file.txt','w',encoding='utf-8') as f:
#     s = """2023-10-1 晴\n今天学习了python文件操作"""
#     f.write(s)


"""
练习2
"""
# date = input("请输入今天的日期:")
# weather = input("记录天气:")
# text = input("请编写日记:")

# # 今天心情很好，去游泳了，下午又去网吧上个网，晚上和好兄弟啤酒烤鸭
# with open('./files/3file.txt','w',encoding='utf-8') as f:
#     f.write(f"{date} {weather}\n")
#     f.write(f"{text.replace('，','\n\n')}")



"""
练习3
"""

# # 读取bil.txt中的内容
# f = open('./files/bil.txt','r',encoding='utf-8')
# res = f.read()
# f.close()
# # 写入bil.txt.bak中
# f_bak = open('./files/bil.txt.bak','w',encoding='utf-8')
# f_bak.write(res)
# f_bak.flush()

with open('./files/bil.txt','r+',encoding='utf-8') as f,open('./files/bil.txt.bak','w',encoding='utf-8') as f_bak:
    # 备份
    res = f.read()
    f_bak.write(res)

    # 内容删除
    s = ""   
    for line in res.split('\n'):
        # 如果找不到返回-1
        if line.find('测试') == -1:
            s += line + '\n'


    # 回转指针
    f.seek(0)
    # 清空内容
    f.truncate()


    
    # 写入新内容
    f.write(s)